package org.vectrics.recruiter.reporting;



import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.VectricsException;
import org.vectrics.common.db.Criteria;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.reporting.pdf.ReportUtil;
import org.vectrics.company.CompanyPerson;
import org.vectrics.company.CompanyPersonCriteria;
import org.vectrics.company.CompanyPersonGroup;
import org.vectrics.company.CompanyPersonGroupType;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.location.Address;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.company.RecruitCompanyService;
import org.vectrics.user.ContactInfo;
import org.vectrics.user.Person;
import org.vectrics.user.PersonSearchCriteria;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;


/**
 * 
 * @author mmoore
 */
public class EmployeeReport extends RecruitBaseReport {
	public static String EMPLOYEE_USER_TYPE = "employee";
	private transient static Logger log = Logger.getLogger(EmployeeReport.class);
	
	
	
	public EmployeeReport(Domain domain, Locale locale) {
		super(domain, locale);
	}

	protected Rectangle getPageSize() {
		return(PageSize.A4.rotate());
	}


	 
	protected void fill(Document document) throws VectricsException {
		log.debug("User List Report - building");
		try {
			
			document.add(new Paragraph("Employees Report", ReportConstants.titleFont));
			document.add(new Paragraph("", ReportConstants.titleFont));

			log.debug("fill() - setting table properties");
			int userTableWidths[] = {80, 53, 80, 80};
			PdfPTable userTable = new PdfPTable(userTableWidths.length);
			userTable.setHorizontalAlignment(Element.ALIGN_LEFT);
			userTable.setWidthPercentage(100);
			userTable.setWidths(userTableWidths);

			log.debug("fill() - adding table header row");
			addTableHeaderCell(userTable, "Name");
			addTableHeaderCell(userTable, "User Name");
			addTableHeaderCell(userTable, "Roles");
			addTableHeaderCell(userTable, "Employment");
			userTable.setHeaderRows(1);
			
			log.debug("fill() - adding user rows");
			PersonSearchCriteria criteria = CoreServiceLocator.createPersonSearchCriteria();
			criteria = new PersonSearchCriteria();
			criteria.setEmployeesOnly(true);
			criteria.getDomains().clear();
			criteria.addDomain(ThreadProperties.getDomain());
			Collection childDomains = ThreadProperties.getDomain().retrieveChildrenInBranch();
			criteria.getDomains().addAll(childDomains);
			criteria.setVoidedType(Criteria.VOID_NO);
			
			log.debug("Person Search criteria: " + criteria);
			
			int count = CoreServiceLocator.getPersonService().findPersonCount(criteria);
			int pageSize = 15;
			int numberOfPages = count / pageSize;
			for (int i = 0; i < numberOfPages; i++) {
				Iterator iter = CoreServiceLocator.getPersonService().findPersons(criteria, i * pageSize, 
							(i * pageSize) + pageSize - 1).iterator();
				while (iter.hasNext()) {
					Person person = (Person)iter.next();
					log.debug("fill() - adding user...");
					addUserRow(userTable, person);
				}
			}
			log.debug("fill() - adding user table to document");
			document.add(userTable);

		}
		catch(Exception e) {
			log.error("Exception creating pdf document - in fill()", e);
			throw new VectricsException("Exception creating pdf document - fill()", e);
		}
        
	}

	protected void addCompanyRoles(PdfPCell parentCell, Person person) {
    	CompanyPersonCriteria criteria = new CompanyPersonCriteria();
        
		Collection domains = CoreServiceLocator.getSystemService().findAllDomains();
		criteria.setDomains(domains);
		criteria.setPerson(person);
        List companyPersonList = null;
		companyPersonList = CoreServiceLocator.getCompanyService().findCompanyPersons(criteria, 
					0, 50);
		
		PdfPTable table = new PdfPTable(2);
		table.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.setWidthPercentage(100);
		int tableWidths[] = {80, 53};
		try {
			table.setWidths(tableWidths);
			Iterator companyPersonIter = companyPersonList.iterator();
			while (companyPersonIter.hasNext()) {
				CompanyPerson companyPerson = (CompanyPerson)companyPersonIter.next();
				if (companyPerson.getCurrentRole() != null) {
					PdfPCell companyCell = new PdfPCell(new Phrase(companyPerson.getCompany().getName()));
					table.addCell(companyCell);
					PdfPCell roleCell = new PdfPCell(new Phrase(companyPerson.getCurrentRole().getTitle()));
					table.addCell(roleCell);
				}
			}
			parentCell.addElement(table);
		} catch (Exception ex) {
			throw new SystemException("Exception writing company person info to document");
		}
	}
    
	
	protected void setupHeaderFooter(Document document) throws VectricsException {
	}


	protected void addTableHeaderCell(PdfPTable table, String title) {
		log.debug("addTableHeaderCell()");
		PdfPCell hdrCell = new PdfPCell(new Phrase(title, ReportConstants.stdBoldFont));
		hdrCell.setBackgroundColor(ReportConstants.TABLE_HEAD_COLOR);
		table.addCell(hdrCell);	
	}
	   

	protected void addUserRow(PdfPTable userTable, Person person) {
		log.info("addUserRow() - person: " + person);
		Color color = new Color(255, 255, 255);
		
		PdfPCell cell = new PdfPCell(ReportUtil.createPhrase(person.getName(), ReportConstants.stdFont));
		cell.setBackgroundColor(color);
		userTable.addCell(cell);	

		String userName = "";
		if (person.getUser() != null)
			userName = person.getUser().getUserName();
		cell = new PdfPCell(ReportUtil.createPhrase(userName, ReportConstants.stdFont));
		cell.setBackgroundColor(color);
		userTable.addCell(cell);	


		String roles = makeRolesSummary(person);
		cell = new PdfPCell(ReportUtil.createPhrase(roles, ReportConstants.stdFont));
		cell.setBackgroundColor(color);
		userTable.addCell(cell);	

		cell = new PdfPCell();
		this.addCompanyRoles(cell, person);
		userTable.addCell(cell);
	}   


	
	private String makeRolesSummary(Person person) {
		String roleSummary = "";
		List companyGroups = CoreServiceLocator.getPersonService().findCompanyGroupsForPerson(person);
		Iterator iter = companyGroups.iterator();
		while (iter.hasNext()) {
			CompanyPersonGroup group = (CompanyPersonGroup)iter.next();
			String groupName = this.getPhrase(group.getCompanyPersonGroupType().getDescriptionCode());
			roleSummary += groupName;
			roleSummary += " ";
		}
		return(roleSummary);
	}	



}
